import { Injectable } from '@angular/core';
import {Observable, Subscription, throwError} from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { LocalStorageService } from '@base/services/local-storage.service'

@Injectable({
    providedIn: 'root'
})

export class AuthService {
    endpoint = 'http://127.0.0.1:8000/';
    headers = new HttpHeaders().set('Content-Type', 'application/json');
    currentUser = {};

    constructor(
        private http: HttpClient,
        private readonly localStorageService: LocalStorageService,
        public router: Router
    ) {
    }

    // Sign-up
    signUp(email: string, password: string): Observable<any> {
        const api = `${this.endpoint}/login`;
        return this.http.post(api, {email, password})
            .pipe(
                catchError(this.handleError)
            )
    }

    // Sign-in
    signIn(loginForm: any): Subscription {
        return this.http.post<any>(`${this.endpoint}/login`, {loginForm})
            .subscribe((res: any) => {
                this.localStorageService.setItem('access_token', res.data.token)
            })
    }

    getToken() : any{
        return localStorage.getItem('access_token');
    }

    get isLoggedIn(): boolean {
        const authToken = localStorage.getItem('access_token');
        return (authToken !== null) ? true : false;
    }

    doLogout() :any{
        const removeToken = localStorage.removeItem('access_token');
        if (removeToken == null) {
            this.router.navigate(['log-in']);
        }
    }

    // User profile
    getUserProfile(id): Observable<any> {
        const api = `${this.endpoint}/user-profile/${id}`;
        return this.http.get(api, { headers: this.headers }).pipe(
            map((res: Response) => {
                return res || {}
            }),
            catchError(this.handleError)
        )
    }

    // Error
    handleError(error: HttpErrorResponse) :any{
        let msg = '';
        if (error.error instanceof ErrorEvent) {
            // client-side error
            msg = error.error.message;
        } else {
            // server-side error
            msg = `Error Code: ${error.status}\nMessage: ${error.message}`;
        }
        return throwError(msg);
    }
}